import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { glInterceptors, AxiosRequestConfigExtends } from './typing'

import { ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading.js'

class GLRequest {
  instance: AxiosInstance
  interceptors?: glInterceptors
  loading?: LoadingInstance
  showLoading: boolean

  constructor(config: AxiosRequestConfigExtends) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? false
    // 请求的执行顺序  后添加的先执行  这里先执行 实例的request 再执行 全局的request
    // 响应的执行顺序  先添加的先执行  这里先执行 全局的response 再执行 实例的response

    // 全局拦截器
    this.instance.interceptors.request.use(
      config => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: 'Loading···'
          })
        }
        return config
      },
      err => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: 'Loading···'
          })
        }
        return err
      }
    )

    this.instance.interceptors.response.use(
      res => {
        if (this.showLoading) {
          this.loading?.close()
        }
        return res
      },
      err => {
        if (this.showLoading) {
          this.loading?.close()
        }
        return err
      }
    )

    // 下面两个是实例拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptors,
      this.interceptors?.requestInterceptorsCatch
    )

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptors,
      this.interceptors?.responseInterceptorsCatch
    )
  }

  // 单独请求
  request<T>(config: AxiosRequestConfigExtends<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptors) {
        config = config.interceptors.requestInterceptors(config)
      }

      this.showLoading = config.showLoading ?? false

      this.instance
        .request<any, T>(config)
        .then(res => {
          if (config.interceptors?.responseInterceptors) {
            res = config.interceptors.responseInterceptors(res)
          }
          resolve(res)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
  get<T>(config: AxiosRequestConfigExtends<T>): Promise<T> {
    return this.request({ ...config, method: 'GET' });
  }
  post<T>(config: AxiosRequestConfigExtends<T>): Promise<T> {
    return this.request({ ...config, method: 'POST' });
  }
  delete<T>(config: AxiosRequestConfigExtends<T>): Promise<T> {
    return this.request({ ...config, method: 'DELETE' });
  }
  patch<T>(config: AxiosRequestConfigExtends<T>): Promise<T> {
    return this.request({ ...config, method: 'PATCH' });
  }
}

export default GLRequest
